<template>
  <div>
    <common-head :title="$route.name"/>
    <div class="order-container">
      <van-contact-card
        :type="contactState"
        :name="contactMan.linkMan"
        :tel="contactMan.mobile"
        @click="onEdit"
      />
      <van-card v-for="item in items" :key="item.id"
        :num="item.number"
        :price="item.price"
        :title="item.name"
        :thumb="item.pic"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchAddress, fetchCart, fetchAddressInfo } from '_api'
import { getToken } from '../../utils'
export default {
  data () {
    return {
      contactState: 'add', // 控制是否添加收货人还是修改收货人
      items: [], // 订单中的商品
      contactMan: {}// 默认收货人
    }
  },
  created () {
    this.fetchAddress()
    this.fetchCarts()
  },
  methods: {
    // 添加收货人
    onEdit () {
      this.$router.push('/orderContact')
    },
    // 请求购物车数据
    fetchCarts () {
      fetchCart({ token: getToken() }).then(res => {
        if (res.data.code === 0) {
          const arr = res.data.data.items
          this.items = arr.filter(item => item.selected)
        }
      })
    },
    // 获取收货人列表
    fetchAddress () {
      if (this.$route.query.id) {
        fetchAddressInfo({
          id: this.$route.query.id,
          token: getToken()
        }).then(res => {
          if (res.data.code === 0) {
            this.contactMan = res.data.data.info
            this.contactState = 'edit'
          }
        })
        return
      }
      fetchAddress({ token: getToken() }).then(res => {
        if (res.data.code === 0) {
          const contacts = res.data.data.result
          // 找到默认联系人
          const defaultMan = contacts.find(item => item.isDefault)
          if (defaultMan) {
            this.contactMan = defaultMan
            this.contactState = 'edit'
          } else {
            this.contactState = 'add'
          }
        }
      })
    }
  },
  components: { CommonHead }

}
</script>

<style lang="scss" scoped>

</style>
